package fb.chatter.main;

import java.io.IOException;
import java.util.Date;
import java.util.Properties;

import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.search.FlagTerm;

import fb.chatter.constant.Constant;

public class A {

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		Properties props = System.getProperties();
		props.setProperty("mail.store.protocol", "imaps");
		try {
			Session session = Session.getDefaultInstance(props, null);
			Store store = session.getStore("imaps");
			store.connect("imap.gmail.com", Constant.CURRENT_USER_NAME, Constant.CURRENT_PASSWORD);

			Folder inboxFolder = store.getFolder("INBOX");
			inboxFolder.open(Folder.READ_ONLY);

			FlagTerm ft = new FlagTerm(new Flags(Flags.Flag.SEEN), false);

			// Message[] messages = inboxFolder.getMessages();
			Message[] messages = inboxFolder.search(ft);
			for (int i = 0; i < messages.length; i++) {
				Message message = messages[i];
				Date receivedDate = message.getReceivedDate();
				Date currentDate = new Date();
				if (currentDate.getTime() - receivedDate.getTime() < 24 * 3600 * 1000) {
					System.out.println("==============================");
					System.out.println("Email #" + (i + 1));
					System.out.println("Subject: " + message.getSubject());
					System.out.println("From: " + message.getFrom()[0]);
					
					Multipart mp = (Multipart)messages[i].getContent();  
//					Object p = mp.getBodyPart(i).getContent(); 
					
//					System.out.println("Text: " + p.toString());
					System.out.println("Text: " + mp.getBodyPart(0).getContent().toString());
//					System.out.println("Text: " + mp.getBodyPart(1).getContent().toString());
				}
			}

			inboxFolder.close(false);
			store.close();
		} catch (NoSuchProviderException e) {
			e.printStackTrace();
			System.exit(1);
		} catch (MessagingException e) {
			e.printStackTrace();
			System.exit(2);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
